package com.cn.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

import com.cn.model.Property;
import com.cn.model.ShoppingCart;
import com.cn.model.User;
import com.cn.validator.ShowGoodsValidator;
import com.cn.validator.SubmitOrderValidator;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

public class ShoppingCartController extends Controller {
	public void index() {
		render("shopCart.jsp");
	}
	
	/*
	 * 拦截器
	 * 验证用户登录信息
	 */
	@Before(ShowGoodsValidator.class)
	/**
	 * 显示购物车的货物
	 */
	public void showGoods() {
		/*
		 * 将用户名存储到session
		 */
		String username = getSessionAttr("user");
		/*
		 * 通过用户名寻找用户id
		 */
		List<User> user = User.dao.find("SELECt * FROM USER WHERE username='"
				+ username + "'");
		int id = user.get(0).get("id");
		/*
		 * 通过连接查询，查找购物车的商品信息
		 */
		List<Record> lists = (List<Record>) Db
				.find("SELECT shoppingcart.id,username,number,Rom,Ram,Color,pName,iPrice, pDesc,Pimg "
						+ "FROM USER u,shoppingcart,commodity  "
						+ "WHERE u.id="
						+ id
						+ " AND u.id = shoppingcart.`uid`AND shoppingcart.`pid` = commodity.`id`");
		/*
		 * 将查找的结果集set进request中
		 */
		setAttr("lists", lists);
		/*
		 * 渲染到购物车页面
		 */
		render("shopCart.jsp");
	}
	/**
	 * 删除购物车的商品
	 */
	public void delGoods() {
		/*
		 * 获取商品id
		 */
		int Id = getParaToInt("id");
		/*
		 * 根据查找商品id删除购物车中在数据库中的商品信息
		 */
		ShoppingCart.dao.deleteById(Id);
		/*
		 * 获取session中用户的用户名
		 */
		String username = getSessionAttr("user");
		/*
		 * 通过用户名查找用户id
		 */
		List<User> user = User.dao.find("SELECt * FROM USER WHERE username='"
				+ username + "'");
		int id = user.get(0).get("id");
		/*
		 * 将删除后购物车的信息重新显示到购物车页面
		 */
		List<Record> lists = (List<Record>) Db
				.find("SELECT shoppingcart.id,username,number,Rom,Ram,Color,pName,iPrice, pDesc,Pimg "
						+ "FROM USER u,shoppingcart,commodity  "
						+ "WHERE u.id="
						+ id
						+ " AND u.id = shoppingcart.`uid`AND shoppingcart.`pid` = commodity.`id`");
		setAttr("lists", lists);
		setAttr("message", "/Shopping/shoppingCart/showGoods");
		renderJson();
	}
	/**
	 * 渲染到订单页面
	 */
	public void settlements(){
		render("sendCart.jsp");
	}
	/**
	 * 结算页面处理
	 */
	public void settlement(){
		String username = getSessionAttr("user");
		List<User> user = User.dao.find("SELECt * FROM USER WHERE username='"+ username + "'");
		int id = user.get(0).get("id");
		Integer[] arr = getParaValuesToInt("arr[]");
		Integer[] num = getParaValuesToInt("count[]");
		List<Object> lists = new ArrayList<Object>();
		/*
		 * 个人理解：
		 * 通过试验知道list是分配好固定内存
		 * 而jfinal的record是动态分配内存，
		 * 相当于动态的javabean 
		 */
//		List<DingDanBean> lists = new ArrayList<DingDanBean>();
//		Map<String,Object> map = new HashMap<String,Object>();
		for(int i = 0; i < arr.length; i++) {
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.append("SELECT pid,username,Rom,Ram,Color,pName,iPrice, pDesc,Pimg ");
			stringBuilder.append("FROM USER u,shoppingcart,commodity ");
			stringBuilder.append("WHERE u.id=");
			stringBuilder.append(id);
			stringBuilder.append(" AND u.id = shoppingcart.`uid`AND shoppingcart.`pid` = commodity.`id` AND pid=");
			stringBuilder.append(arr[i]);
			Record record =  Db.find(stringBuilder.toString()).get(0);
			record.set("num", num[i]);
			lists.add(record);
//			((Record)lists.get(0)).set("num", num[i]);
//			map.put("lists"+i, list);
		}
		System.out.println(((Record)lists.get(0)).get("num"));
		setSessionAttr("lists", lists);
		System.out.println("去结算！");
		renderJson();
	}
	/*
	 * 验证信息是否填定完整
	 */
	@Before(SubmitOrderValidator.class)
	/**
	 * 提交订单页面处理
	 */
	public void submitOrder(){
		/*
		 * 通过用户名获得用户id
		 */
		String username = getSessionAttr("user");
		List<User> user = User.dao.find("SELECt * FROM USER WHERE username='"+ username + "'");
		int uid = user.get(0).get("id");
		/*
		 * 前台获得参数
		 */
		String province = getPara("province");
		String city = getPara("city");
		String detailAddress = getPara("detailAddress");
		String receiver = getPara("receiver");
		String phone = getPara("receiverPhone");
		String allcounts = getPara("totalSum");
		String address = province+"省"+city+"市"+detailAddress;
		
		/*
		 * 产生订单id,时间戳+随机数
		 */
		Date date = new Date();
		Random rand=new Random();
		String nextInt = String.valueOf(rand.nextInt(10));
		for(int i = 1; i <= 5; i++ ){
			nextInt += String.valueOf(rand.nextInt(10));
		}
		int n = Integer.valueOf(nextInt);
		String num = String.format("%05d", n);
		
		String orderNum = num+date.getTime();
		/*
		 * 获得当前时间，转为数据库类型
		 */
		java.sql.Date nowDate = new java.sql.Date(new Date().getTime());
		List<Object> lists = getSessionAttr("lists");
		/**
		 * 订单数据存储到数据库
		 */
		for (int j = 0; j < lists.size(); j++) {
			Record record = new Record().set("orderNum",orderNum)
					.set("address", address)
					.set("receiver", receiver)
					.set("phone", phone)
					.set("allcounts", allcounts)
					.set("date", nowDate)
					.set("uid", uid)
					.set("pid", ((Record)(lists.get(j))).get("pid"))
					.set("state",1);
			Db.save("orderform", record);
			Db.deleteById("shoppingcart", ((Record)(lists.get(j))).get("pid"));
			List<Property> property = Property.dao.find("SELECt * FROM property "
					+ "WHERE pid="+((Record)(lists.get(j))).get("pid")+" "
							+ "AND Rom='"+((Record)(lists.get(j))).get("Rom")+"' "
									+ "AND Color='"+((Record)(lists.get(j))).get("Color")+"'");
			Integer pNum = (Integer)property.get(j).get("pNum");
			Integer pnum = (Integer)((Record)(lists.get(j))).get("num");
			int resultpNum = pNum-pnum;
			Db.update("UPDATE  property  SET pNum="+resultpNum+" "
					+ "WHERE (pid="+((Record)(lists.get(j))).get("pid")+" "
							+ "AND Rom='"+((Record)(lists.get(j))).get("Rom")+"'"
									+ " AND Color='"+((Record)(lists.get(j))).get("Color")+"')");
			//System.out.println(pNum-pnum);
		}
		setAttr("message", "/Shopping/shoppingCart/submitOrder");
		renderJson();
	}
}
